#!/bin/sh

## a script somewhat like OpenBSD everyday system checks.
## %_loc: _root_/opt/etc/rcs %

## $Id: mmng.sh 12 2007-10-06 04:28:53Z dhg $

CK_TMP=/var/confs
SYSTEM_RC_DIR=/etc
INSTALL_DATA="/usr/bin/install -Scp -m 0644"
SHA_CMD="/sbin/sha256 -q"

recur_cook ()
{
	for node in ${1}/*; do
		if [ -d $node ]; then
			cd $node
			recur_cook $node
		else
			if [ -r $node -a -f $node ]; then
				cook $node
			fi
		fi
	done
}

cook ()
{
	tmp=`echo $node | sed "s/\//#/g"`

	if [ ! -e ${CK_TMP} ]; then
		mkdir -p ${CK_TMP}
	else
		if [ ! -d ${CK_TMP} ]; then
			printf "\n>>> ${CK_TMP} exits and is not a directory!\n"
			printf ">>> go check if it is a regular file.\n"
			printf ">>> we need this directory to store files.\n\n"
			exit 0
		fi
	fi

	tmp_file=${CK_TMP}/${tmp}
	tmp_current=${tmp_file}.current
	tmp_backup=${tmp_file}.backup

	if [ -r $tmp_current -a -r ${tmp_file}.sha ]; then

		src_ck_sum=`${SHA_CMD} $node`
		tar_ck_sum=`cat ${tmp_file}.sha`
		eval $(stat -L -s $node) >&-
		src_size=$st_size
        eval $(stat -s $tmp_current) >&-
        tar_size=$st_size

		if [ ! "$src_ck_sum" = "$tar_ck_sum" -o ! $src_size -eq $tar_size ]; then

			echo "*****************************************"
			echo
			echo "<<< $node"
			echo "<<<"
			echo "<<< is different from"
			echo "<<<"
			echo "<<< $tmp_current"
			echo
			echo ">>> $node"
			echo ">>> will be installed in '${CK_TMP}' as current."
			echo
			echo "*****************************************"
			echo

			diff -upN $tmp_current $node
			$INSTALL_DATA $node $tmp_current
			$SHA_CMD $node > ${tmp_file}.sha

		fi

	else

		$INSTALL_DATA $node $tmp_backup
		$INSTALL_DATA $node $tmp_current
		$SHA_CMD $node > ${tmp_file}.sha

	fi
}

recur_cook $SYSTEM_RC_DIR

exit 0
